package com.kevin.controller.controller.system;

import cn.dev33.satoken.annotation.SaCheckPermission;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.kevin.common.api.R;
import com.kevin.common.constants.Constants;
import com.kevin.common.enums.MenuTypeEnum;
import com.kevin.service.config.StpUserHolder;
import com.kevin.service.entity.SysMenu;
import com.kevin.service.entity.SysUser;
import com.kevin.service.service.SysMenuService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * 菜单管理
 *
 * @author 阿沐 babamu@126.com
 */
@RestController
@RequestMapping("sys/menu")
@Api(tags = "菜单管理")
@AllArgsConstructor
public class SysMenuController {
    private final SysMenuService sysMenuService;

    @GetMapping("nav")
    @ApiOperation(value = "菜单导航")
    public R<List<SysMenu>> nav() {
        SysUser user = StpUserHolder.getUserFromSession();
        return R.ok(sysMenuService.getUserMenuList(user.getId(), user.getSuperAdmin(), MenuTypeEnum.MENU.getValue()));
    }

    @GetMapping("authority")
    @ApiOperation(value = "用户权限标识")
    public R<List<String>> authority() {
        SysUser user = StpUserHolder.getUserFromSession();
        return R.ok(sysMenuService.getUserAuthority(user.getId(), user.getSuperAdmin()));
    }

    @GetMapping("list")
    @ApiOperation(value = "菜单列表")
    @SaCheckPermission(value = "sys:menu:list")
    public R<List<SysMenu>> list(Integer type) {
        return R.ok(sysMenuService.list(Wrappers.lambdaQuery(SysMenu.builder().type(type).build())));
    }

    @GetMapping("{id}")
    @ApiOperation(value = "信息")
    @SaCheckPermission(value = "sys:menu:info")
    public R<SysMenu> get(@PathVariable("id") Long id) {
        SysMenu entity = sysMenuService.getById(id);

        // 获取上级菜单名称
        if (!Constants.ROOT.equals(entity.getPid())) {
            SysMenu parentEntity = sysMenuService.getById(entity.getPid());
            entity.setParentName(parentEntity.getName());
        }

        return R.ok(entity);
    }

    @PostMapping
    @ApiOperation(value = "保存")
    @SaCheckPermission(value = "sys:menu:save")
    public R<String> save(@RequestBody @Valid SysMenu vo) {
        sysMenuService.save(vo);

        return R.ok();
    }

    @PutMapping
    @ApiOperation(value = "修改")
    @SaCheckPermission(value = "sys:menu:update")
    public R<String> update(@RequestBody @Valid SysMenu vo) {
        sysMenuService.updateById(vo);
        return R.ok();
    }

    @DeleteMapping("{id}")
    @ApiOperation(value = "删除")
    @SaCheckPermission(value = "sys:menu:delete")
    public R<String> delete(@PathVariable("id") Long id) {
        sysMenuService.removeById(id);
        return R.ok();
    }
}
